package com.lu.banktrade.servic.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.banktrade.mapper.AccountMapper;
import com.lu.banktrade.pojo.dto.LogDTO;
import com.lu.banktrade.pojo.dto.SavingDTO;
import com.lu.banktrade.quque.LogQueue;
import com.lu.banktrade.servic.AccountService;
import com.lu.banktrade.utils.ResultUtil;
import entity.Account;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;

/**
 * @author L
 *
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Resource
    private LogQueue logQueue;

    @Resource
    private AccountMapper accountMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultUtil saving(SavingDTO dto) {

        //通过条件获得账户信息
        LambdaQueryWrapper<Account> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Account::getUid,dto.getUid());
        queryWrapper.eq(Account::getCardno,dto.getCardno());
        Account account = accountMapper.selectOne(queryWrapper);
        if (account == null) {
            return ResultUtil.fail("账户不存在");
        }
        //加钱操作
        BigDecimal bigDecimal = new BigDecimal(String.valueOf(dto.getMoney()));
        account.setRemaining(account.getRemaining().add(bigDecimal));
        int update = accountMapper
                .update(account, new LambdaQueryWrapper<Account>().eq(Account::getAid, account.getAid()));

        //日志记录操作
        if (update>0){
            LogDTO logDTO = new LogDTO();
            logDTO.setAid(String.valueOf(account.getAid()));
            logDTO.setTradeTime(LocalDate.now());
            logDTO.setTradeType("存款");
            logDTO.setTradeDigest("用户id为("+dto.getUid()+")的用户存了("+dto.getMoney()+")");
            logDTO.setTradeMoney(String.valueOf(dto.getMoney()));
            String jsonString = JSONObject.toJSONString(logDTO);
            logQueue.addLog(jsonString);
        }

        return update>0?ResultUtil.success("操作成功"):ResultUtil.fail("操作失败");
    }
}
